package com.dhcc.consumer.listener.ttlListener;

import java.io.IOException;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Argument;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

@Component
public class MessageTTLListener01 {

	@RabbitListener(bindings = @QueueBinding(
								value = @Queue(
										name = "ttl-direct-queue",
										durable = "true",
										arguments = @Argument(name = "x-message-ttl",value = "30000",type = "java.lang.Long")),
								exchange = @Exchange(name = "ttl-direct-exchange",type = ExchangeTypes.DIRECT,durable = "true"),
								key = {"info"}
	))
	public void listenerSimple(Message message, Channel channel) {
		// message分装了消息
		byte[] body = message.getBody();
		String content = new String(body);
		long deliveryTag = message.getMessageProperties().getDeliveryTag();
		try {
			// 模拟进行业务处理产生异常
//			int i = 1 / 0;

			System.out.println("MessageNoneAckListener01...msg01 ----->" + content);

			// 给RabbitMQ服务端返回ack
			/**
			 * 第一个参数：表示消息的标签，用来标识消息的唯一性 第二个参数：是否进行批量应答
			 * 第二个参数：是否需要进行批量应答
			 */
			channel.basicAck(deliveryTag, true);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				// 响应unack
				// 第三个参数，是否需要将消息重新加入到队列里
				channel.basicNack(deliveryTag, true, true);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
